import { useEffect } from 'react'
import echarts from './echarts'

function useECharts(domRef, option) {
  useEffect(() => {
    if (!domRef) return
    const myChart = echarts.init(domRef.current)
    option && myChart.setOption(option)

    function debounce(fn, delay = 300) {
      let timer = null
      return function () {
        if (timer) clearTimeout(timer)
        timer = setTimeout(fn, delay)
      }
    }

    const handleResize = debounce(() => {
      myChart && myChart.resize()
    }, 100)

    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
      myChart && myChart.dispose()
      console.log('destroy instance')
    }
  }, [domRef, option])
}

export default useECharts
